package com.jxd.petMgr.servlet;


import com.jxd.petMgr.model.PetOwner;
import com.jxd.petMgr.service.IPetOwnerService;
import com.jxd.petMgr.service.impl.PetOwnerServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * ClassName: ${NAME}
 * Description:
 *
 * @author: hqy
 * @Date: 2021/11/17
 * @version: 1.0
 */
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
//    IAdminSer iAdminSer = new AdminServiceimpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String username =  request.getParameter("username");
        String pwd = request.getParameter("password");
        IPetOwnerService petOwnerService = new PetOwnerServiceImpl();
        PetOwner petOwner = petOwnerService.login(username,pwd);

//        Admin admin = new Admin(username,pwd);
        HttpSession session = request.getSession();
//        PrintWriter pw = response.getWriter();
        if (petOwner != null) {
            //登录成功跳到新页面
//            pw.write("登录成功");
            Cookie cookieUsername = new Cookie("username",username);
            Cookie cookiePwd = new Cookie("pwd",pwd);
            response.addCookie(cookiePwd);
            response.addCookie(cookieUsername);


//            session.setAttribute("username",petOwner.getName());
//            session.setAttribute("userId",petOwner.getId());
            session.setAttribute("petOwner",petOwner);
            response.sendRedirect("petList.jsp");
//            response.sendRedirect("petList.jsp?name="+username);
//            request.setAttribute("name",username);
//            request.getRequestDispatcher("petOwner.jsp").forward(request,response);

        } else {
            //失败返回原页面
            //使用重定向可以指定跳转页面
//            response.sendRedirect("login.html");
            //使用转发
            //可以将数据封装到request对象中，封装进去的数据就会恭喜给下一个页面
            request.setAttribute("msg","用户名或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request,response);



//            pw.write("登录失败");
        }
//        pw.flush();
//        pw.close();
    }
}
